<?php

namespace App\Repositories;

use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class RedEnvelopeRepository {

    public function globalDetail()
    {
        $result = app('model_red_envelope_global_config')->first();

        return $result;
    }

    public function updateGlobalConfig(Array $params)
    {
        $model = app('model_red_envelope_global_config');
        if (!empty($params['id'])) {
            $model = $model->find($params['id']);
        }
        $model->setAttribute("rule_type", $params["rule_type"]);
        $model->setAttribute("base_money", $params["base_money"]);
        $model->setAttribute("reward_count", $params["reward_count"]);
        $model->setAttribute("gift_id", $params["gift_id"]);
        $model->setAttribute("limit_user_level", $params["limit_user_level"]);
        $model->setAttribute("user_count_limit", $params["user_count_limit"]);
        $model->setAttribute("disable", $params["disable"]);
        $model->setAttribute("daily_start_time", $params["daily_start_time"]);
        $model->setAttribute("daily_end_time", $params["daily_end_time"]);
        $model->setAttribute("second_daily_start_time", $params["second_daily_start_time"]);
        $model->setAttribute("second_daily_end_time", $params["second_daily_end_time"]);
        $model->setAttribute("start_time", $params["start_time"]);
        $model->setAttribute("end_time", $params["end_time"]);

        $affectsRows = $model->save();
        if($affectsRows) {
            $this->notify();
            return $affectsRows;
        };
        throw new BasicException(20008);
    }

    // 通知服务配置发生了变更
    private function notify() {
        Redis::publish("red_envelope_global_config_change","");
    }


    /**
     * 管理员后台查询配置数据
     */
    public function getRoomLogQueryList(Array $params) {
        $whereArr = [];
        if (!empty($params['serial'])) {
            $whereArr[] = ['id', "=", $params['serial']];
        }

        if (!empty($params['start_date'])) {
            $whereArr[] = ['end_time', ">=", $params['start_date']];
        }

        if (!empty($params['end_date'])) {
            $whereArr[] = ['end_time', "<=", $params['end_date']];
        }

        $whereFunc = function ($query) use ($params) {
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $result = app('model_red_envelope_room_log')->where($whereArr)->where($whereFunc)->orderBy('id','desc')->paginate($perPage, ['*'], '', $page);


        $userLogMap = [];
        if (count($result) > 0) {
            $roomLogIds = [];
            foreach ($result as $item) {
                $roomLogIds[] = $item->id;
            }

            $userLogRes = app('model_red_envelope_user_log')
                ->whereIn("room_log_id", $roomLogIds)
                ->groupBy("room_log_id")
                ->select(["room_log_id", DB::raw("count(user_id) as count")])->get();

            if (!empty($userLogRes)) {
                $userLogMap = array_column($userLogRes->toArray(), null, "room_log_id");
            }
        }


        foreach ($result as $item) {
            if (isset($userLogMap[$item->id])) {
                $item->join_user_count = $userLogMap[$item->id]['count'];
            } else {
                $item->join_user_count = 0;
            }
        }

        return $result;
    }

    public function userLogRecord($roomLogId) {
        $userLogModel = app('model_red_envelope_user_log');
        $userDataModel = app('model_user_data');

        $userList = $userLogModel
            ->from($userLogModel->getTable() . " as t1")
            ->leftJoin(DB::raw($userDataModel->getTable() . " as t2"), "t1.user_id", "=", "t2.user_id")
            ->select(["t1.*", "t2.nickname", "t2.user_code"])
            ->where("t1.room_log_id", $roomLogId)->get();

        return $userList;
    }

}